package org.jeecg.modules.icms.invoice.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.icms.invoice.dto.IcmsInvoiceDetailDto;

import org.jeecg.modules.icms.invoice.entity.IcmsInvoiceHeader;
import org.jeecg.modules.icms.invoice.entity.IcmsInvoiceTitle;
import org.jeecg.modules.icms.invoice.service.IIcmsInvoiceDetailService;
import org.jeecg.modules.icms.invoice.service.IIcmsInvoiceHeaderService;
import org.jeecg.modules.icms.invoice.service.IIcmsInvoiceTitleService;
import org.jeecg.modules.icms.invoice.vo.IcmsInvoiceHeaderVo;
import org.jeecg.modules.icms.util.HandleExcelInfo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


 /**
 * @Description: 发票头表
 * @Author: jeecg-boot
 * @Date:   2024-01-10
 * @Version: V1.0
 */
@Api(tags="发票头表")
@RestController
@RequestMapping("/invoice/icmsInvoiceHeader")
@Slf4j
public class IcmsInvoiceHeaderController extends JeecgController<IcmsInvoiceHeader, IIcmsInvoiceHeaderService> {

	 @Resource
	 private IIcmsInvoiceHeaderService icmsInvoiceHeaderService;

	 @Resource
	 private IIcmsInvoiceTitleService iIcmsInvoiceTitleService;

	 @Resource
	 private IIcmsInvoiceDetailService iIcmsInvoiceDetailService;

	 @Resource
	 private HandleExcelInfo handleExcelInfo;

	 /**
	  * 分页列表查询
	  *
	  * @param
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 //@AutoLog(value = "发票头表-分页列表查询")
	 @ApiOperation(value = "发票头表-分页列表查询", notes = "发票头表-分页列表查询")
	 @GetMapping(value = "/list")
	 public Result<IPage<IcmsInvoiceHeaderVo>> queryPageList(
			 IcmsInvoiceHeaderVo icmsInvoiceHeaderVo,
			 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
			 HttpServletRequest req) {
		 return Result.ok(icmsInvoiceHeaderService.queryAll(icmsInvoiceHeaderVo, pageNo, pageSize, req));
	 }

	 /**
	  * 添加
	  *
	  * @param icmsInvoiceHeader
	  * @return
	  */
	 @AutoLog(value = "发票头表-添加")
	 @ApiOperation(value = "发票头表-添加", notes = "发票头表-添加")
	 @RequiresPermissions("invoice:icms_invoice_header:add")
	 @PostMapping(value = "/add")
	 public Result<String> add(@RequestBody IcmsInvoiceHeader icmsInvoiceHeader) {
		 icmsInvoiceHeaderService.save(icmsInvoiceHeader);
		 return Result.OK("添加成功！");
	 }

	 /**
	  * 编辑
	  *
	  * @param icmsInvoiceHeader
	  * @return
	  */
	 @AutoLog(value = "发票头表-编辑")
	 @ApiOperation(value = "发票头表-编辑", notes = "发票头表-编辑")
	 @RequiresPermissions("invoice:icms_invoice_header:edit")
	 @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
	 public Result<String> edit(@RequestBody IcmsInvoiceHeader icmsInvoiceHeader) {
		 icmsInvoiceHeaderService.updateById(icmsInvoiceHeader);
		 return Result.OK("编辑成功!");
	 }

	 /**
	  * 通过id删除
	  *
	  * @param id
	  * @return
	  */
	 @AutoLog(value = "发票头表-通过id删除")
	 @ApiOperation(value = "发票头表-通过id删除", notes = "发票头表-通过id删除")
	 @RequiresPermissions("invoice:icms_invoice_header:delete")
	 @DeleteMapping(value = "/delete")
	 public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
		 icmsInvoiceHeaderService.removeById(id);
		 return Result.OK("删除成功!");
	 }

	 /**
	  * 批量删除
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "发票头表-批量删除")
	 @ApiOperation(value = "发票头表-批量删除", notes = "发票头表-批量删除")
	 @RequiresPermissions("invoice:icms_invoice_header:deleteBatch")
	 @DeleteMapping(value = "/deleteBatch")
	 public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
		 this.icmsInvoiceHeaderService.removeByIds(Arrays.asList(ids.split(",")));
		 return Result.OK("批量删除成功!");
	 }

	 /**
	  * 通过id查询
	  *
	  * @param id
	  * @return
	  */
	 //@AutoLog(value = "发票头表-通过id查询")
	 @ApiOperation(value = "发票头表-通过id查询", notes = "发票头表-通过id查询")
	 @GetMapping(value = "/queryById")
	 public Result<IcmsInvoiceHeader> queryById(@RequestParam(name = "id", required = true) String id) {
		 IcmsInvoiceHeader icmsInvoiceHeader = icmsInvoiceHeaderService.getById(id);
		 if (icmsInvoiceHeader == null) {
			 return Result.error("未找到对应数据");
		 }
		 return Result.OK(icmsInvoiceHeader);
	 }

	 /**
	  * 导出excel
	  *
	  * @param request
	  * @param icmsInvoiceHeader
	  */
	 @RequiresPermissions("invoice:icms_invoice_header:exportXls")
	 @RequestMapping(value = "/exportXls")
	 public ModelAndView exportXls(HttpServletRequest request, IcmsInvoiceHeader icmsInvoiceHeader) {
		 return super.exportXls(request, icmsInvoiceHeader, IcmsInvoiceHeader.class, "发票头表");
	 }

	 /**
	  * 通过excel导入数据
	  *
	  * @param
	  * @param
	  * @return
	  */
	 @Transactional(rollbackFor = {Exception.class})
	 @RequiresPermissions("invoice:icms_invoice_header:importExcel")
	 @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	 public Result<?> importExcel(MultipartFile file) throws Exception {
		 Workbook workbook = handleExcelInfo.getWorkBook(file);
		 //获取sheet
		 int sheetNum = workbook.getNumberOfSheets();
		 if (sheetNum == 0)
			 throw new JeecgBootException("工作表为空！");
		 //一次处理一个sheet
		 for (int sheetIndex = 0; sheetIndex < sheetNum; sheetIndex++) {
			 Sheet sheet = workbook.getSheetAt(sheetIndex);
			 // 处理开票单title数据 位于第3-8行的第一列  将数据拼接成字符串后采用正则表达式解析
			 String titleInfo = "";
			 for (int titleRow = 2; titleRow < 8; titleRow++) {
				 if (sheet.getRow(titleRow) == null)
					 throw new JeecgBootException(sheet.getSheetName() + "表中：抬头格式错误或缺失信息");
				 titleInfo += sheet.getRow(titleRow).getCell(0);
			 }
			 //第一个开票备注行和零件名称、件号在一行 否则提示格式错误
			 String[] headerInfoFlag = {"开票含税单价（元）", "无税单价（元）", "无税金额（元）", "税率%", "税额（元）", "价税合计（元）", "是否报关", "开票备注"};
			 //第8-14列为校验列
			 for (int k = 7, m = 0; k < 15 && m < 8; k++, m++) {
				 if (!sheet.getRow(9).getCell(k).toString().equals(headerInfoFlag[m])) {
					 throw new JeecgBootException("第10行开票头格式错误，请严格按照模板填写！");
				 }
			 }

			 //解析开票单抬头
			 IcmsInvoiceTitle icmsInvoiceTitle = iIcmsInvoiceTitleService.addTitleInfo(titleInfo, sheet);
			 iIcmsInvoiceTitleService.save(icmsInvoiceTitle);

			 //读取所有的header和detail数据
			 ImportParams params = new ImportParams();
			 params.setSheetNum(1);//读取的sheet数量
			 params.setStartSheetIndex(sheetIndex);//读取的sheet索引
			 params.setTitleRows(9);
			 params.setHeadRows(1);
			 List<IcmsInvoiceDetailDto> list = ExcelImportUtil.importExcel(file.getInputStream(), IcmsInvoiceDetailDto.class, params);

			 List<IcmsInvoiceDetailDto> icmsInvoiceDetail = new ArrayList<IcmsInvoiceDetailDto>();
			 //相邻开票单可能存在空行间隔 为方便处理，去掉表格里的空行，存入新的列表
			 for (IcmsInvoiceDetailDto page : list) {
				 if (!handleExcelInfo.checkObjAllFieldsIsNull(page)) icmsInvoiceDetail.add(page);
			 }

			 //记录所有含“零件名称”所在的行 将其作为行识别标志 用于获取icmsInvoiceDetail列表中的header和detail数据
			 List<Integer> ljmcRows = new ArrayList<>();
			 for (int ljmcRow = 0; ljmcRow < icmsInvoiceDetail.size(); ljmcRow++) {
				 IcmsInvoiceDetailDto icmsInvoiceDetailDto = icmsInvoiceDetail.get(ljmcRow);
				 if (icmsInvoiceDetailDto.getPartName().equals("零件名称")) {
					 ljmcRows.add(ljmcRow);
				 }
			 }

			 //处理header信息
			 List<IcmsInvoiceHeader> icmsInvoiceHeaderList = icmsInvoiceHeaderService.addHeaderInfo(sheet, icmsInvoiceDetail, ljmcRows, icmsInvoiceTitle);
			 icmsInvoiceHeaderService.saveBatch(icmsInvoiceHeaderList);

			 //处理datail信息
			 iIcmsInvoiceDetailService.addDetailInfo(sheet, icmsInvoiceDetail, ljmcRows, icmsInvoiceHeaderList);
		 }
		 return Result.ok("文件导入成功！");
	 }


 }